package com.systop.ltbook.fileattch.webapp;

import java.io.File;
import java.util.Date;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.systop.core.util.DateUtil;
import com.systop.core.webapp.struts2.action.JsonCrudAction;
import com.systop.core.webapp.upload.UpLoadUtil;
import com.systop.ltbook.fileattch.model.FileAttch;
import com.systop.ltbook.fileattch.service.FileAttchManager;

@SuppressWarnings("serial")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class FileAttchAction extends JsonCrudAction<FileAttch, FileAttchManager> {

	private File attch;

	private String attchFileName;

	private String attchFolder = "/uploadFiles/fileAttch/";
	
	private Integer handleFileId = null;

	public String upLoadFile() {
		attchFolder += DateUtil.getDateToString(new Date(), "yyyy-MM") + "/";
		handleFileId = 0;
		if (attch != null) {
			FileAttch file = new FileAttch();
			String filePath = UpLoadUtil.doUpload(attch,
					attchFileName, attchFolder, getServletContext());
			file.setName(attchFileName);
			file.setPath(filePath);
			file.setCreatetime(new Date());
			getManager().save(file);
			handleFileId = file.getId();
		}
		return "upload_success";
	}
	
	/**
	 * 删除附件
	 */
	public String remove(){
		if (getModel()!= null && getModel().getId() != null){
			if(getModel().getType() == null){
				String path = getModel().getPath();
				path = getServletContext().getRealPath(path);
				File f = new File(path);
				if (f.exists()){
					if(!f.delete()){
						//如果文件删除失败需要记录吗？应该需要吧，得先记录下，以后再删
					}
				}
				getManager().remove(getModel());
			}else{
				addActionError("文件被引用,删除失败!");
			}
			
			if (isJsonReq()){
				handleFileId = getModel().getId();
				return "ajax-del-att";
			}
		}
		return SUCCESS;
	}

	public File getAttch() {
		return attch;
	}

	public void setAttch(File attch) {
		this.attch = attch;
	}

	public String getAttchFileName() {
		return attchFileName;
	}

	public void setAttchFileName(String attchFileName) {
		this.attchFileName = attchFileName;
	}

	public Integer getHandleFileId() {
		return handleFileId;
	}
}
